// cloud/functions/join_room/index.js  
const cloud = require('wx-server-sdk');  
  
cloud.init();  
const db = cloud.database();  
  
// 封装一个函数来创建用户信息对象  
const createUserInfo = (openid) => {  
  return {  
    openid,  
    avatarUrl: 'cloud://avalon-cloud-1gg01hi5d0e8cec0.6176-avalon-cloud-1gg01hi5d0e8cec0-1330536532/images/icons/hostAvatar.png',  
    nickname: '玩家'  
  };  
};  
  
exports.main = async (event, context) => {  
  const { roomId, userOpenid } = event; // 获取房间号和用户的openid  
  
  // 查找房间  
  const room = await db.collection('rooms').where({ roomId }).get();  
  
  if (room.data.length === 0) {  
    return {  
      message: '房间不存在'  
    };  
  }  
  
  const roomData = room.data[0];  
  const { currentUserCount, selectedCapacity, userList } = roomData;  
  
  // 检查房间是否已满  
  if (currentUserCount >= selectedCapacity) {  
    return {  
      message: '房间已满，无法加入',  
      currentUserCount,  
      selectedCapacity,  
      userList  
    };  
  }  
  
  // 检查userOpenid是否已存在于userList中  
  const userExists = userList.some(user => user.openid === userOpenid);  
  
  if (userExists) {  
    return {  
      message: '用户已在房间中，无需重复加入',  
      currentUserCount,  
      selectedCapacity,  
      userList  
    };  
  }  
  
  // 创建新用户信息对象  
  const newUserInfo = createUserInfo(userOpenid);  
  
  // 更新房间信息  
  const updatedRoomData = await db.collection('rooms').doc(roomData._id).update({  
    data: {  
      currentUserCount: currentUserCount + 1, // 增加已有用户数  
      userList: [...userList, newUserInfo] // 添加新用户到用户列表  
    }  
  });  
  
  return {  
    message: '成功加入房间',  
    currentUserCount: currentUserCount + 1,  
    selectedCapacity,  
    userList: [...userList, newUserInfo]  
  };  
};